<template>
	<div class="connector-detail">
		<div class="flex justify-between items-center mb-4">
			<h4 class="text-xl font-semibold">{{ connector.title }}</h4>
			<div class="flex gap-2">
				<a-button :icon="h(EditOutlined)" type="primary" @click="handleEdit">修改</a-button>
				<a-button :icon="h(DeleteOutlined)" danger @click="handleDelete">删除</a-button>
			</div>
		</div>

		<a-tabs :activeKey="activeKey" @change="(key) => (activeKey = key)">
			<a-tab-pane key="1" tab="基本信息">
				<div class="bg-white rounded-lg shadow p-6">
					<div class="space-y-4">
						<div class="flex items-center">
							<span class="font-medium w-24">连接器名称:</span>
							<span>{{ connector.data.name }}</span>
						</div>
						<div class="flex items-center">
							<span class="font-medium w-24">连接器类型:</span>
							<span>{{ connector.data.type }}</span>
						</div>
						<div class="flex items-center">
							<span class="font-medium w-24">连接状态:</span>
							<span v-if="status === 'checking'" class="text-yellow-500">检查中...</span>
							<span v-else-if="status === 'normal'" class="text-green-500">正常</span>
							<span v-else class="text-red-500">异常</span>
						</div>
						<div class="flex items-start">
							<span class="font-medium w-24">描述信息:</span>
							<span class="flex-1">{{ connector.data.description || '暂无描述' }}</span>
						</div>
					</div>
				</div>
			</a-tab-pane>

			<a-tab-pane key="2" tab="数据明细">
				<!-- MySQL连接器显示表列表 -->
				<div v-if="connector?.data.type === 'MYSQL'" class="overflow-auto p-2">
					<a-table
						:columns="tableColumns"
						:data-source="tableList"
						:loading="tableLoading"
						:pagination="false"
						:scroll="{ y: 600 }"
						:sticky="true"
						bordered
						size="small"
					>
						<template #bodyCell="{ column, record }">
							<template v-if="column.dataIndex === 'tableType'">
								<span>
									<a-tag
										:color="
											record.tableType === 'BASE TABLE' ? 'green' : record.tableType === 'VIEW' ? 'blue' : 'default'
										"
									>
										{{
											record.tableType === 'BASE TABLE' ? '表' : record.tableType === 'VIEW' ? '视图' : record.tableType
										}}
									</a-tag>
								</span>
							</template>
						</template>
					</a-table>
				</div>

				<!-- API连接器显示接口列表 -->
				<div
					v-else-if="connector?.data.type === 'LOCAL_API' || connector?.data.type === 'EXTERNAL_API'"
					class="overflow-auto p-2"
				>
					<a-table
						:columns="apiColumns"
						:data-source="apiList"
						:loading="apiLoading"
						:pagination="false"
						:scroll="{ y: 600 }"
						:sticky="true"
						bordered
						size="small"
					>
						<template #bodyCell="{ column, record }">
							<template v-if="column.dataIndex === 'method'">
								<a-tag :color="getMethodColor(record.method)">
									{{ record.method }}
								</a-tag>
							</template>
							<template v-if="column.dataIndex === 'requireAuth'">
								<a-tag :color="record.requireAuth ? 'red' : 'green'">
									{{ record.requireAuth ? '需要认证' : '无需认证' }}
								</a-tag>
							</template>
							<template v-if="column.dataIndex === 'module'">
								<a-tag color="blue">{{ record.module }}</a-tag>
							</template>
						</template>
					</a-table>
				</div>

				<div v-else class="text-gray-400">当前连接器不支持查看数据明细</div>
			</a-tab-pane>
		</a-tabs>
	</div>
</template>

<script setup>
	import { h, ref, watch } from 'vue'
	import { DeleteOutlined, EditOutlined } from '@ant-design/icons-vue'
	import { message, Modal } from 'ant-design-vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'

	// Props
	const props = defineProps({
		connector: {
			type: Object,
			required: true
		},
		status: {
			type: String,
			default: 'checking'
		}
	})

	// Emits
	const emit = defineEmits(['edit', 'delete', 'refresh'])

	// 数据
	const activeKey = ref('1')
	const tableList = ref([])
	const tableLoading = ref(false)
	const apiList = ref([])
	const apiLoading = ref(false)

	// MySQL表格列定义
	const tableColumns = [
		{
			title: '名称',
			dataIndex: 'tableName'
		},
		{
			title: '类型',
			dataIndex: 'tableType'
		},
		{
			title: '字段数',
			dataIndex: 'columnCount'
		},
		{
			title: '表描述',
			dataIndex: 'tableDescription'
		},
		{
			title: '索引数',
			dataIndex: 'indexCount'
		}
	]

	// API接口表格列定义
	const apiColumns = [
		{
			title: 'API路径',
			dataIndex: 'apiPath',
			width: 200,
			ellipsis: true
		},
		{
			title: '请求方法',
			dataIndex: 'method',
			width: 80,
			align: 'center'
		},
		{
			title: '所属模块',
			dataIndex: 'module',
			width: 100,
			align: 'center'
		},
		{
			title: 'API描述',
			dataIndex: 'apiDescription',
			ellipsis: true
		},
		{
			title: '权限要求',
			dataIndex: 'requireAuth',
			width: 100,
			align: 'center'
		}
	]

	// 监听标签页切换
	watch(activeKey, async (newKey) => {
		if (newKey === '2' && props.connector?.data) {
			await loadDataDetails()
		}
	})

	// 加载数据详情
	const loadDataDetails = async () => {
		const connectorType = props.connector.data.type

		if (connectorType === 'MYSQL') {
			// 获取MySQL表列表
			tableLoading.value = true
			try {
				tableList.value = await dataConnectorApi.tablesWithMeta({ id: props.connector.data.id })
			} catch (error) {
				console.error('获取数据表列表失败:', error)
				tableList.value = []
			} finally {
				tableLoading.value = false
			}
		} else if (connectorType === 'LOCAL_API' || connectorType === 'EXTERNAL_API') {
			// 获取API接口列表
			apiLoading.value = true
			try {
				apiList.value = await dataConnectorApi.apisWithMeta({ id: props.connector.data.id })
			} catch (error) {
				console.error('获取API接口列表失败:', error)
				apiList.value = []
			} finally {
				apiLoading.value = false
			}
		}
	}

	// 编辑连接器
	const handleEdit = () => {
		emit('edit', props.connector.data)
	}

	// 删除连接器
	const handleDelete = () => {
		Modal.confirm({
			title: '确认删除',
			content: '是否确认删除该数据连接器？删除后数据不可恢复！',
			okText: '确认',
			cancelText: '取消',
			okButtonProps: { danger: true },
			onOk: async () => {
				try {
					await dataConnectorApi.delete([{ id: props.connector.data.id }])
					message.success('删除成功')
					emit('delete', props.connector.data.id)
				} catch (error) {
					console.error('删除失败:', error)
					message.error('删除失败')
				}
			}
		})
	}

	// 获取请求方法颜色
	const getMethodColor = (method) => {
		const colors = {
			GET: 'green',
			POST: 'blue',
			PUT: 'orange',
			DELETE: 'red',
			PATCH: 'purple'
		}
		return colors[method] || 'default'
	}

	// 暴露方法给父组件
	defineExpose({
		loadDataDetails
	})
</script>

<style scoped>
	.connector-detail {
		padding: 0;
	}
</style>
